package com.emm.yixun.mobile.ui.analysis;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.MainProjectAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetDealHouseList;
import com.emm.yixun.mobile.model.GetProjectList;
import com.emm.yixun.mobile.model.GetProjectList.ProjectList;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.PercentFormatter;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * <p>
 * <b>Title：</b> 成交、存量房源分析
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午4:12:51
 */
public class DealHousingActivity extends SwipeBackActivity implements OnChartValueSelectedListener {

    private static final String TAG = "DealHousingActivity";

    private String TypeHousing = "1";

    /**
     * 标题
     */
    TextView title_main;

    TextView null_date5, null_date6;

    /**
     * back按钮
     */
    ImageView back_btn;

    /**
     * 打开条件选择弹出框
     */
    LinearLayout open_layout_analysis;

    TextView name_time_analysis;

    ArrayList<Integer> bgcolor = new ArrayList<Integer>();

    /**
     * 数据列表
     */
    private ArrayList<String> list = new ArrayList<String>();

    /**
     * 数据列表每项所对应的百分比
     */
    private ArrayList<Float> list2 = new ArrayList<Float>();

    private ArrayList<String> list3 = new ArrayList<String>();
    /**
     * 扇形图
     */
    private PieChart chart1_1, chart1_2;

    /**
     * 侧滑关闭框架
     */
    private SwipeBackLayout mSwipeBackLayout;

    @Override
    protected void onResume() {
        BaseActivity.activity = this;
        super.onResume();
    }

    /**
     * <p>
     * <b>Title：</b> 初始化图像显示的色值
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:09:45
     */
    private void SetColor() {
        bgcolor.add(Color.parseColor("#FFE76E"));
        bgcolor.add(Color.parseColor("#FFC499"));
        bgcolor.add(Color.parseColor("#FFB468"));
        bgcolor.add(Color.parseColor("#FF9048"));
        bgcolor.add(Color.parseColor("#F64A2A"));
        bgcolor.add(Color.parseColor("#FA7388"));
        bgcolor.add(Color.parseColor("#F63C7F"));
        bgcolor.add(Color.parseColor("#F43560"));
        bgcolor.add(Color.parseColor("#CC1F1A"));
        bgcolor.add(Color.parseColor("#740D0C"));
        bgcolor.add(Color.parseColor("#C6F4FF"));
        bgcolor.add(Color.parseColor("#67C3D5"));
        bgcolor.add(Color.parseColor("#5199AA"));
        bgcolor.add(Color.parseColor("#009796"));
        bgcolor.add(Color.parseColor("#009868"));
        bgcolor.add(Color.parseColor("#8CD3E7"));
        bgcolor.add(Color.parseColor("#1FBBD3"));
        bgcolor.add(Color.parseColor("#006EA8"));
        bgcolor.add(Color.parseColor("#005AA6"));
        bgcolor.add(Color.parseColor("#5B5377"));
    }

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.dealhousing_activity);
        TypeHousing = getIntent().getStringExtra("TypeHousing");

        SetSwipeBackLayout(mSwipeBackLayout);

        BaseActivity.activity = this;

        SetColor();
        initView();

        SetRelativiLayoutPadding(R.id.main_head_top_rela);

        initBnt();
        getDealHouseList("1");

    }

    /**
     * <p>
     * <b>Title：</b> 初始化view
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:10:04
     */
    private void initView() {
        title_main = (TextView) findViewById(R.id.title_main);
        if ("1".equals(TypeHousing))
            title_main.setText("成交房源分析");
        else
            title_main.setText("存量房源分析");
        back_btn = (ImageView) findViewById(R.id.back_btn);
        open_layout_analysis = (LinearLayout) findViewById(R.id.open_layout_analysis);
        name_time_analysis = (TextView) findViewById(R.id.name_time_analysis);
        chart1_1 = (PieChart) findViewById(R.id.chart1_1);
        chart1_1.setNoDataText(" ");
        chart1_2 = (PieChart) findViewById(R.id.chart1_2);
        chart1_2.setNoDataText(" ");
        null_date5 = (TextView) findViewById(R.id.null_date5);
        null_date6 = (TextView) findViewById(R.id.null_date6);
    }

    /**
     * <p>
     * <b>Title：</b> 初始化监听事件
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:10:12
     */
    private void initBnt() {
        back_btn.setVisibility(View.VISIBLE);
        back_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        open_layout_analysis.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SetsortPopu();
            }
        });

    }

    View viewproject;
    PopupWindow popuproject;
    /**
     * 时间
     */
    private int SelectPostion = 0;

    /**
     * <p>
     * <b>Title：</b> 条件选择弹出框
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:10:26
     */
    public void SetsortPopu() {
        viewproject = LayoutInflater.from(DealHousingActivity.this).inflate(R.layout.mainproject_popu, null);
        popuproject = new PopupWindow(viewproject, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
        popuproject.setFocusable(true);
        popuproject.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popuproject.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popuproject.showAtLocation(open_layout_analysis, Gravity.TOP, 0, 0);
        popuproject.setFocusable(true);
        popuproject.setOutsideTouchable(true);
        viewproject.setFocusable(true);
        viewproject.setFocusableInTouchMode(true);
        viewproject.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    popuproject.dismiss();
                    EmmApplication.setLog(DealHousingActivity.this);
                }
                return false;
            }
        });

        viewproject.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popuproject.dismiss();
                EmmApplication.setLog(DealHousingActivity.this);
            }
        });

        ListView popu_list = (ListView) viewproject.findViewById(R.id.popu_list);
        RelativeLayout top_relativelayout = (RelativeLayout) viewproject.findViewById(R.id.top_relativelayout);
        SetViewPaddingHeight(top_relativelayout, 100);
        ArrayList<ProjectList> ll = new ArrayList<ProjectList>();

        ProjectList m = new ProjectList();
        m.setProjectCode("1");
        m.setProjectName("住宅");
        ll.add(m);

        ProjectList m2 = new ProjectList();
        m2.setProjectCode("2");
        m2.setProjectName("别墅");
        ll.add(m2);

        ProjectList m3 = new ProjectList();
        m3.setProjectCode("3");
        m3.setProjectName("车位");
        ll.add(m3);

        final GetProjectList list = new GetProjectList();
        list.setProjectList(ll);

        MainProjectAdapter adapter = new MainProjectAdapter(DealHousingActivity.this, list);
        popu_list.setAdapter(adapter);
        adapter.SetType(1);
        if (list.getProjectList().size() >= (SelectPostion + 1)) {
            adapter.SeleCt(SelectPostion);
            name_time_analysis.setText(list.getProjectList().get(SelectPostion).getProjectName());
        } else {
            adapter.SeleCt(0);
            name_time_analysis.setText(list.getProjectList().get(0).getProjectName());
        }
        popu_list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popuproject.dismiss();
                SelectPostion = position;
                EmmApplication.setLog(DealHousingActivity.this);
                name_time_analysis.setText(list.getProjectList().get(position).getProjectName());
                int numbertype = SelectPostion + 1;
                Log.v(TAG, "numbertype:==>" + numbertype);
                // 调用接口
                getDealHouseList(list.getProjectList().get(position).getProjectCode());
            }
        });
    }

    /**
     * <p>
     * <b>Title：</b> 配置扇形图属性,第一次在加载数据完成之后触发
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param mChart
     * @param type
     * @author tangxin
     * @date 2016年12月7日 下午2:11:34
     */
    private void SetSettingChart(PieChart mChart, int type) {
        mChart.setUsePercentValues(true);
        mChart.setHoleColorTransparent(true);
        mChart.setHoleRadius(55);
        if (type == 0) {
            mChart.setHoleColor(Color.parseColor("#ffffff"));
            mChart.setCenterText("100%");
        } else {
            mChart.setHoleColor(Color.parseColor("#00ffffff"));
            mChart.setCenterText(" ");
        }
        mChart.setDescription("");
        mChart.setDrawCenterText(true);
        mChart.setDrawHoleEnabled(true);
        mChart.setRotationAngle(0);
        mChart.setRotationEnabled(true);
        mChart.setOnChartValueSelectedListener(this);
        mChart.setX(EmmApplication.dip2pxf(-100));
        setData(mChart);
        mChart.animateXY(1000, 1000);
        Legend l = mChart.getLegend();
        l.setPosition(LegendPosition.RIGHT_OF_CHART);
        l.setXEntrySpace(20f);
        l.setYEntrySpace(4f);
    }

    /**
     * <p>
     * <b>Title：</b> 调用动画效果
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param mChart
     * @author tangxin
     * @date 2016年12月7日 下午2:11:44
     */
    private void animate(PieChart mChart) {
        mChart.invalidate();
    }

    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
        if (e == null)
            return;
        Log.i("VAL SELECTED", "Value: " + e.getVal() + ", xIndex: " + e.getXIndex() + ", DataSet index: "
                + dataSetIndex);
    }

    public void onNothingSelected() {
        Log.i("PieChart", "nothing selected");
    }

    /**
     * <p>
     * <b>Title：</b> 给统计图设置数据
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param mChart
     * @author tangxin
     * @date 2016年12月7日 下午2:11:50
     */
    private void setData(PieChart mChart) {
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < list2.size(); i++) {
            yVals1.add(new Entry(list2.get(i), i));
        }
        ArrayList<String> xVals = new ArrayList<String>();

        PieDataSet dataSet = new PieDataSet(yVals1, "");
        dataSet.setSliceSpace(3f);
        for (int i = 0; i < list.size(); i++)
            xVals.add(EmmApplication.removeWYuan(list.get(i)) + "\t\t" + list3.get(i) + "\t\t"
                    + ("(" + EmmApplication.drop2("" + list2.get(i)) + "%" + ")"));
        dataSet.setDrawValues(false);
        mChart.setDrawSliceText(false);
        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int i = 0; i < list.size(); i++) {
            colors.add(bgcolor.get(i));
        }

        dataSet.setColors(colors);
        PieData data = new PieData(xVals, dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.BLACK);
        mChart.setData(data);
        mChart.highlightValues(null);
        mChart.setNoDataTextDescription(" ");
        mChart.invalidate();
    }

    /**
     * 查询成交房源分析
     */
    GetDealHouseList getdeal;

    /**
     * <p>
     * <b>Title：</b> 查询成交房源分析
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param houseType
     * @author tangxin
     * @date 2016年12月7日 下午2:12:22
     */
    private void getDealHouseList(String houseType) {
        if ("1".equals(TypeHousing))
            EmmApplication.updateUrl("getDealHouseList");
        else
            EmmApplication.updateUrl("getStockHouseList");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("houseType", houseType);
        map.put("projectCode", EmmApplication.getProjectCode());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        if ("1".equals(TypeHousing))
            Log.v(TAG, "getDealHouseList-->post:" + EmmApplication.urlStr + "?body=" + jsonstr);
        else
            Log.v(TAG, "getStockHouseList-->post:" + EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.hideDialogForLoading();
                Loading.showDialogForLoading(DealHousingActivity.this, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v(TAG, "content===>" + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                getdeal = JSONObject.parseObject(resData.toString(), GetDealHouseList.class);

                if ("1".equals(getdeal.getResult())) {
                    Log.v("获取成功", "");
                    if (null != getdeal.getAreaSegmentList()) {
                        list.clear();
                        list2.clear();
                        list3.clear();
                        double countall = 0;
                        for (int i = 0; i < getdeal.getAreaSegmentList().size(); i++) {
                            countall += Double.valueOf(getdeal.getAreaSegmentList().get(i).getAreaSegmentNum())
                                    .doubleValue();
                        }
                        for (int i = 0; i < getdeal.getAreaSegmentList().size(); i++) {
                            list.add(getdeal.getAreaSegmentList().get(i).getAreaSegment());
                            list2.add((float) (Double.valueOf(getdeal.getAreaSegmentList().get(i).getAreaSegmentNum())
                                    .doubleValue() / countall) * 100);
                            float f = (float) (Double.valueOf(getdeal.getAreaSegmentList().get(i).getAreaSegmentNum())
                                    .doubleValue() / countall) * 100;
                            Log.v(TAG, f + "======");
                            list3.add(getdeal.getAreaSegmentList().get(i).getAreaSegmentNum());
                        }
                        if (list.size() <= 0) {
                            null_date5.setVisibility(View.VISIBLE);
                        } else {
                            null_date5.setVisibility(View.INVISIBLE);
                            SetSettingChart(chart1_1, 0);
                            animate(chart1_1);
                        }
                    } else {
                        null_date5.setVisibility(View.VISIBLE);
                        list.clear();
                        list2.clear();
                        list3.clear();
                        SetSettingChart(chart1_1, 1);
                        animate(chart1_1);
                    }

                    if (null != getdeal.getLumpSumList()) {
                        list.clear();
                        list2.clear();
                        list3.clear();
                        double countall = 0;
                        for (int i = 0; i < getdeal.getLumpSumList().size(); i++) {
                            countall += Double.valueOf(getdeal.getLumpSumList().get(i).getLumpSumNum()).doubleValue();
                        }
                        for (int i = 0; i < getdeal.getLumpSumList().size(); i++) {
                            list.add(getdeal.getLumpSumList().get(i).getLumpSum());
                            list2.add((float) (Double.valueOf(getdeal.getLumpSumList().get(i).getLumpSumNum())
                                    .doubleValue() / countall) * 100);
                            list3.add(getdeal.getLumpSumList().get(i).getLumpSumNum());
                        }
                        if (list.size() <= 0) {
                            null_date6.setVisibility(View.VISIBLE);
                        } else {
                            null_date6.setVisibility(View.INVISIBLE);
                            SetSettingChart(chart1_2, 0);
                            animate(chart1_2);
                        }
                    } else {
                        null_date6.setVisibility(View.VISIBLE);
                        list.clear();
                        list2.clear();
                        list3.clear();
                        SetSettingChart(chart1_2, 1);
                        animate(chart1_2);
                    }
                } else {
                    EmmApplication.T(getdeal.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + getdeal.getErrorCode().toString() + "errorMsg:"
                            + getdeal.getErrorMsg().toString());
                }
            }
        });
    }

}
